package model;

import util.IDGenerator;
import Repository.Repository;
import Repository.RepositoryFactory;
import constants.SMSConstants;
import factory.SMSObjectFactory;

public class Approved implements SMSObjectState
{
	private final String NAME = "Approved";
	
	RuleSelector ruleSelector;
	NextStateCalculator stateCalculator;
	Repository repository;

	
	@Override
	public void execute(SMSObject smsObj) 
	{
		if(smsObj instanceof Opportunity)
		{
			System.out.println("Executing Approved State...");
			ruleSelector =  new ImportRuleSelector(smsObj);
			stateCalculator = new NextStateCalculator();
			SMSObjectState newState = stateCalculator.getNextState(smsObj,ruleSelector);
		//	System.out.println("New state..." + newState.getStateName());
			
			if(newState.getStateName().equals(NAME)){
				System.out.println("****Contract cannot be imported as it doesnot comply to the rules****");
				return;
			}
			
			
			SMSObjectFactory factory = new SMSObjectFactory();
			Opportunity o = (Opportunity)smsObj;
			
			Contract contract = (Contract)factory.createSMSObject(SMSConstants.CONTRACT);
			contract.setAccount(o.getAccount());
			contract.setDescription(o.getDescription());
			contract.setCurrentState(newState);
			contract.setManagedByUser(smsObj.getManagedByUser());
			
			long id = IDGenerator.getNextId();
			contract.setSmsObjId(id);
			contract.setCost(o.getQuote().getPrice() * o.getQuote().getQuantity());
			repository = RepositoryFactory.getRepository(SMSConstants.CONTRACT);
			repository.insert(new Long(id),contract);	
			System.out.println("Successfully imported the contract" );
			
			repository = RepositoryFactory.getRepository(SMSConstants.OPPORTUNITY);
			
			smsObj.setCurrentState(new Finalized());
			repository.update(smsObj.getSmsObjId(), smsObj);
			
			
			
		}else if(smsObj instanceof Contract){
		//	Contract c = (Contract)smsObj;
			    ruleSelector =  new FinalizeRuleSelector();
				stateCalculator = new NextStateCalculator();
				SMSObjectState newState = stateCalculator.getNextState(smsObj,ruleSelector);
				smsObj.setCurrentState(newState);				
				repository = RepositoryFactory.getRepository(SMSConstants.CONTRACT);
				repository.update(smsObj.getSmsObjId(), smsObj);
				
				System.out.println("Successfully finalized contract.");
			
		}		
	}
	
	public String getStateName(){
		return NAME;
	}
}
